<?php
/**
 * Created by PhpStorm.
 * User: linhui
 * Date: 2016/12/13
 * Time: 21:41
 */


/**
 * 生成密码
 * @param $password
 * @return string
 */
function sp_password($password)
{
    return strlen($password) > 20 ? $password : sha1(md5($password));
}

/**
 * 生成token
 * @return string
 */
function token()
{
    return md5(time().rand(0,9999));
}

function getLoginInfo()
{
    return session('user');
}

/**
 * 输出时间
 * @param $time
 * @param string $format
 * @return bool|false|string
 */
function sp_date($time, $format = 'Y-m-d H:i:s')
{
    return $time ? date($format, $time) : false;
}

/**
 * 检查权限
 * @param string $uri 路由
 * @param string $adminId 用户ID
 * @return mixed
 */
function authCheck($uri, $adminId){
    $access = new \Org\Util\Access();
    return $access->check($uri, $adminId);
}

/**
 * 下载函数
 * @param string file 文件全路径
 * @param string name 保存文件名
 * @return empty
 *
 */
function download($file, $name=''){
    $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
    $filePath = realpath($file);

    $fp = fopen($filePath,'rb');

    if(!$filePath || !$fp){
        header('HTTP/1.1 404 Not Found');
        echo "This file is can't download:file is not exists";
        exit;
    }

    $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
    $encoded_filename = urlencode($fileName);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);

    header('HTTP/1.1 200 OK');
    header( "Pragma: public" );
    header( "Expires: 0" );
    header("Content-type: application/octet-stream");
    header("Content-Length: ".filesize($filePath));
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($filePath));

    $ua = $_SERVER["HTTP_USER_AGENT"];
    if (preg_match("/MSIE/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    } else if (preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
    } else {
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
    }

    // ob_end_clean(); <--有些情况可能需要调用此函数
    // 输出文件内容
    fpassthru($fp);
    exit;
}

/**
 * 表格转换数组
 * @param  [type] $file [description]
 * @return [type]       [description]
 */
function excelTrans($file, $mode = 'normal', $row = 0) {
    require_once './ThinkPHP/Library/Org/Util/Excel.class.php';
    $config = array(
        'class_root'=>'./ThinkPHP/Library/Org/Util/PHPExcel',
    );
    set_time_limit(0);
    ini_set("memory_limit","300M");
    $a = new \Excel($config);
    $arr = $a->excelToArray($file, $mode, $row);

    return $arr;
}

/**
 * 数据转换成Excel
 */
function ArrayToExcel($data, $path, $save_name = null){
    require_once './ThinkPHP/Library/Org/Util/Excel.class.php';
    $config = array(
        'class_root'=>'./ThinkPHP/Library/Org/Util/PHPExcel',
    );
    set_time_limit(0);
    ini_set("memory_limit","1G");
    $a = new \Excel($config);
    $tmp = array();
    foreach($data as &$v){
        $tmp_v = array();
        foreach($v as $val){
            $tmp_v[] = $val;
        }
        $tmp[] = $tmp_v;
    }
    $save_name = $save_name ? $save_name :time().'.xls';
    $arr = $a->arrayToExcel($tmp, $save_name, array('savepath'=>$path));
    return $path.$save_name;
}


/**
 * 更多字符隐藏
 * @param $str
 * @param int $start
 * @param $length
 * @param string $charset
 * @param bool $suffix
 * @return string
 */
function more_hidden($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    $str = strip_tags(html_entity_decode($str));
    preg_match_all('/&\w+;/m', $str, $matches);
    $matches = array_unique($matches[0]);
    foreach($matches as $item) {
        $str = str_replace($item, html_entity_decode($item), $str);
    }

    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    $fix='';
    if(strlen($slice) < strlen($str)){
        $fix='...';
    }
    return $suffix ? $slice.$fix : $slice;
}

/**
 * 索引数组按特定键值排序
 * @param $arr
 * @param $key
 * @param bool $asc
 * @return mixed
 */
function sortByKey(&$arr, $key, $asc = true){
    $len=count($arr);
    //该层循环控制 需要冒泡的轮数
    for($i=1;$i<$len;$i++)
    { //该层循环用来控制每轮 冒出一个数 需要比较的次数
        for($k=0;$k<$len-$i;$k++)
        {
            if($asc ?
                $arr[$k][$key]>$arr[$k+1][$key] :
                $arr[$k][$key]<$arr[$k+1][$key]
            )
            {
                $tmp=$arr[$k+1];
                $arr[$k+1]=$arr[$k];
                $arr[$k]=$tmp;
            }
        }
    }
    return $arr;
}
/**
 * 提交POST数据
 * 如果使用Curl 你需要改一改你的php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 *
 * @param   string   服务接口地址
 * @param   mixed    提交数据
 * @param   array    http头信息
 * @param   boolean  是否SSL传输
 * @return  mixed    返回结果
 **/
function http_post($gateway_url, $req_data, $optional_headers = null, $isSSL = false) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $gateway_url);                //配置网关地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);                          //设置post提交
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);            //post传输数据
    if ($optional_headers !== null){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $optional_headers);
    }
    else{
        curl_setopt($ch, CURLOPT_HEADER, 0);                        //过滤HTTP头
    }
    if($isSSL){
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); //SSL版本
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * 获取GET数据
 *
 * @param   string   请求接口和参数
 * @return  mixed    返回结果
 **/
function http_get($url) {
    $ch = curl_init();
    $timeout = 10;

    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    if ( strpos($url, 'https') == 0){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
    }
    $content = curl_exec($ch);
    curl_close($ch);
    if($content) {
        return $content;
    } else {
        return false;
    }
}


/**
 * 递归删除文件夹
 * @param $dir
 * @param string $file_type
 */
function delFile($dir, $file_type = '') {
    if (is_dir($dir)) {
        $files = scandir($dir);
        //打开目录 //列出目录中的所有文件并去掉 . 和 ..
        foreach($files as $filename) {
            if ($filename != '.' && $filename != '..') {
                if (!is_dir($dir . DIRECTORY_SEPARATOR . $filename)) {
                    if (empty($file_type)) {
                        unlink($dir . DIRECTORY_SEPARATOR . $filename);
                    }
                    else {
                        if (is_array($file_type)) {
                            //正则匹配指定文件
                            if (preg_match($file_type[0], $filename)) {
                                unlink($dir . DIRECTORY_SEPARATOR . $filename);
                            }
                        }
                        else {
                            //指定包含某些字符串的文件
                            if (false != stristr($filename, $file_type)) {
                                unlink($dir . DIRECTORY_SEPARATOR . $filename);
                            }
                        }
                    }
                }
                else {
                    delFile($dir . DIRECTORY_SEPARATOR . $filename);
                    rmdir($dir . DIRECTORY_SEPARATOR . $filename);
                }
            }
        }
    }else{
        if (file_exists($dir)) unlink($dir);
    }
}

/**
 * 保存上传信息
 */
function saveUploadInfo($file, $is_admin){
    //保存上传信息
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $image = array('jpg', 'jpeg', 'png', 'gif');
    $excel = array('xls', 'xlsx');
    $word = array('doc', 'docx');
    $type_arr = array('image', 'excel', 'word');
    foreach ($type_arr as $v) {
        if(in_array($ext, $$v)){
            $type = $v;
        }
    }
    $type = isset($type) ? $type : 'else';

    $add = array(
        'file_ext'=>$ext,
        'file_path'=>$file,
        'type'=>$type,
        'upload_time'=>time(),
    );
    if($is_admin){
        $add['upload_uid'] = session('admin_id');
        $admin_info = M('admin')->find($add['upload_uid']);
        $add['extra'] = $admin_info['nickname'].'|';
        $add['user_type'] = 2;
    } else {
        $add['upload_uid'] = session('user_id');
        $user_info = M('user')->find($add['upload_uid']);
        $add['extra'] = $user_info['link_name'].'|'.$user_info['mobile'];
        $add['user_type'] = 1;
    }
    M('Upload')->add($add);

}

/**
 * 上传文件默认规则定义
 */
function sp_upload_init($upload) {
    $allow_max = C('pin_attr_allow_size'); //读取配置
    $allow_exts = explode(',', C('pin_attr_allow_exts')); //读取配置
    $allow_max && $upload->maxSize = $allow_max * 1024;   //文件大小限制

    $allow_exts && $upload->exts = $allow_exts;  //文件类型限制
    $upload->saveRule = 'uniqid';
    return $upload;
}

/**
 * 上传文件
 */
function sp_upload($file, $dir = '', $thumb = array(), $save_rule='uniqid', $is_amdin = false) {
    $upload = new \Think\Upload();
    if ($dir) {
        $upload_path = C('pin_attach_path') . $dir . '/';
        $upload->savePath = $upload_path;
    }
    if ($thumb) {
        $upload->thumb = true;
        $upload->thumbMaxWidth = $thumb['width'];
        $upload->thumbMaxHeight = $thumb['height'];
        $upload->thumbPrefix = '';
        $upload->thumbSuffix = isset($thumb['suffix']) ? $thumb['suffix'] : '_thumb';
        $upload->thumbExt = isset($thumb['ext']) ? $thumb['ext'] : '';
        $upload->thumbRemoveOrigin = isset($thumb['remove_origin']) ? true : false;
    }
    //自定义上传规则
    $upload = sp_upload_init($upload);
    if( $save_rule!='uniqid' ){
        $upload->saveRule = $save_rule;
    }

    if ($result = $upload->uploadOne($file)) {
        $file = $result['savepath'].$result['savename'];
        //保存上传信息
        $upload_dir = str_replace(__ROOT__, '', C('TMPL_PARSE_STRING.__UPLOAD__'));
        saveUploadInfo($upload_dir.$file, $is_amdin);
        return array('error'=>0, 'info'=>C('TMPL_PARSE_STRING.__UPLOAD__').$result['savepath'].$result['savename']);
    } else {
        return array('error'=>1, 'info'=>$upload->getError());
    }
}

/**
 * 后台上传
 */
function sp_admin_upload($file, $dir = '', $thumb = array(), $save_rule='uniqid'){
    return sp_upload($file, $dir, $thumb, $save_rule, true);
}

/**
 * 保存配置文件 数据转字符串
 * @param $arg
 * @return string
 */
function array_to_str($arg)
{
    if(!is_array($arg)){
        return $arg;
    }
    $result = "\narray(\n";
    foreach ($arg as $k => $v) {
        if(is_array($v)){
            $v = array_to_str($v);
            $result .= "'{$k}'=>{$v},\n";
        } else {
            $result .= "'{$k}'=>'{$v}',\n";
        }

    }
    $result .= ")\n";
    return $result;
}

/**
 * 保存到配置文件
 * @param string $path
 * @param array $data
 * @param null $key
 * @return bool
 */
function saveConfigFile($path = '', $data = array(), $key = null){

    //文件不存在就创建
    file_exists($path) || touch($path);
    $file_content = require $path;
    $file_content = is_array($file_content) ? $file_content : array();
    if($key != null){
        $file_content[$key] = $data;
    } else{
        $file_content = $data;
    }
    $put_content = "<?php\nreturn ".array_to_str($file_content).';';

    if(file_put_contents($path, $put_content)){
        return true;
    } else{
        return false;
    }
}

/**
 * 转换对象字符串
 * @param $str
 * @return array|bool
 */
function objstr_array($str){
    if(strpos($str, '{') === false){
        return false;
    }

    $result = array();
    $str = trim(trim($str, '{'), '}');
    $tmp = explode(',', $str);
    if(is_array($tmp)){
        foreach ($tmp as $v) {
            $kv_tmp = explode(':', $v);
            if($kv_tmp[0] && $kv_tmp[1]){
                $result[trim($kv_tmp[0], '"')] = trim($kv_tmp[1], '"');
            }
        }
    }

    return $result;
}

/**
 * 判断是否是手机号
 * @param $str
 * @return bool
 */
function isMobileStr($str){
    return preg_match('/^1[345789]\d{9}$/', $str) ? true : false;
}

/**
 * 数组转为queryString
 * @param $arr
 * @return string
 */
function queryBuilder($arr)
{
    $res = [];
    foreach ($arr as $key => $item) {
        if($item){
            $res[] = $key.'='.$item;
        }
    }
    return join('&', $res);
}

/**
 * 获取七牛云信息
 * @return array
 */
function getQiniuInfo()
{
    $accessKey = C('QINIU.AccessKey');
    $secretKey = C('QINIU.SecretKey');
    $auth = new Qiniu\Auth($accessKey, $secretKey);
    // 空间名  https://developer.qiniu.io/kodo/manual/concepts
    $bucket = C('QINIU.bucket');
    // 生成上传Token
    $token = $auth->uploadToken($bucket);
    return array(
        'accessKey'=>$accessKey,
        'secretKey'=>$secretKey,
        'bucket'=>$bucket,
        'token'=>$token,
        'domain'=>C('QINIU.domain'),
        'qiniu_url'=>C('QINIU.qiniu_url'),
        'key'=>C('QINIU.qiniu_url') ? C('QINIU.qiniu_url').'/'.sha1(time().rand(1000,9999)) : sha1(time().rand(1000,9999)),
    );
}

/**
 * 获取站点信息
 * @return bool|mixed
 */
function getWebsiteInfo()
{
    $model = new \Common\Model\SettingModel();
    return $model->getWebsiteInfo();
}


/**
 * 获取友情链接
 * @return mixed
 */
function getLink()
{
    return M('Link')->where(array('status'=>1,))
        ->order('sort')
        ->field('link_url, link_name')
        ->select();
}

/**
 * 获取当前URL
 * @return string
 */
function currentUrl()
{
    $pageURL = 'http';

    if ($_SERVER["HTTPS"] == "on")
    {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    $pageURL .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    return $pageURL;
    if ($_SERVER["SERVER_PORT"] != "80")
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    }
    else
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}


/**
 * 图片转码base64
 * @param $image_file
 * @return string
 */
function base64EncodeImage ($image_file) {
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

/**
 * 科学记数法转字符串
 * @param $num
 * @return float|string
 */
function NumToStr($num){
    if (stripos($num,'e')===false) return $num;
    $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法，还原成字符串
    $result = "";
    while ($num > 0){
        $v = $num - floor($num / 10)*10;
        $num = floor($num / 10);
        $result   =   $v . $result;
    }
    return $result;
}

/**
 * URL无前缀处理
 * @param $url
 * @param string $prefix
 * @return string
 */
function prefixUrl($url, $prefix = 'http://')
{
    if(preg_match('/^\w+:\/\//', $url)) {
        return $url;
    } else {
        return  $prefix.$url;
    }
}

/**
 * 对部分字进包裹处理
 * @param $str
 * @param $word
 * @param array $wrap
 * @return mixed
 */
function wrapWord($str, $word, $wrap = [])
{
    $result = str_replace($word, $wrap[0].$word.$wrap[1], $str);
    return $result ? $result : $str;
}